package com.scisoft.scan.control.delivery;

import android.Manifest;
import android.app.DatePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import java.util.Calendar;

import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.nlscan.android.scan.ScanManager;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.data.delivery.LogisticsCompanyBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.data.delivery.DeliveryBean;
import com.scisoft.scan.data.delivery.LogisticsInfo;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.SysParameter;
import com.scisoft.scan.ws.WebServiceHelper_Delivery;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class LogisticsActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private TextView tv_save; //保存按钮
    private TextView tv_submit;//发运按钮
    private TextView tv_pz;//拍照

    //表单项
    private ClearEditText et_wldh;//物流单号
    private ClearEditText et_lxr;//联系人
    private ClearEditText et_shdy1;//联系电话
    private TextView et_shsj;//预到货日期
    private ClearEditText et_bz;//备注
    private LinearLayout layout_imagelist;//照片列表

    private LogisticsInfo logisticsInfo;//发运单
    private DeliveryBean deliveryBean;
    private String flag;//2 未处理 3 已完成

    //物流信息
    private Spinner spin_logistics;
    private List<String> LogisticsInfoList = new ArrayList<>(); //物流公司下拉框
    private List<LogisticsCompanyBean> logBeanList = new ArrayList<>();//物流公司列表
    private int selectedDepotNo = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_logistics);

        //参数传递
        Intent intent = getIntent();
        deliveryBean = (DeliveryBean) intent.getSerializableExtra("deliveryBean");
        flag = (String) intent.getSerializableExtra("flag");
        //表单项
        spin_logistics = findViewById(R.id.spin_logistics);
        //物流单号
        et_wldh = findViewById(R.id.et_wldh);
        et_shdy1 = findViewById(R.id.et_shdy1);
        //联系人
        et_lxr =  findViewById(R.id.et_lxr);
        //联系电话
        et_shdy1.setText(deliveryBean.telephone);
        //到货时间
        et_shsj= findViewById(R.id.et_shsj);
        //日期控件
        Calendar calendar = Calendar.getInstance();//调用Calendar类获取年月日
        final int mYear1 = calendar.get(Calendar.YEAR);//年
        final int mMonth1 = calendar.get(Calendar.MONTH) + 1;//月份要加一个一，这个值的初始值是0。不加会日期会少一月。
        final int mDay1 = 1;//日
        et_shsj.setText(mYear1 + "-" + String.format("%02d", mMonth1) + "-" + String.format("%02d", mDay1));
        et_shsj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                DatePickerDialog datePickerDialog = new DatePickerDialog(LogisticsActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                        et_shsj.setText(i + "-" + String.format("%02d", i1 + 1) + "-" + String.format("%02d", i2));
                    }
                }, mYear1, mMonth1 - 1, mDay1);//将年月日放入DatePickerDialog中，并将值传给参数

                datePickerDialog.show();//显示dialog
            }
        });

        //备注
        et_bz = findViewById(R.id.et_bz);

        layout_imagelist = findViewById(R.id.layout_imagelist);
        //下拉框
        QueryLogistics();
        //拍照
        tv_pz = findViewById(R.id.tv_pz);
        tv_pz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加拍照代码
                if(isStoragePermissionGranted()) {
                    takePhoto();
                }

            }
        });
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //提交
        tv_save = findViewById(R.id.tv_save);
        tv_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetData();
                CommonUtil.showPress(LogisticsActivity.this);
                SaveTask saveTask = new SaveTask(LogisticsActivity.this);
                saveTask.execute();
            }
        });
        tv_submit = findViewById(R.id.tv_submit);
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                GetData();
                CommonUtil.showPress(LogisticsActivity.this);
                CommitTask commitTask = new CommitTask(LogisticsActivity.this);
                commitTask.execute();
            }
        });
        //如果已经保存过单据则查询物流单
        if (deliveryBean.deliveryId != null && deliveryBean.deliveryId != "") {
            //查询已经保存的信息
            CommonUtil.showPress(LogisticsActivity.this);
            QueryTask queryTask = new QueryTask(LogisticsActivity.this);
            queryTask.execute();
        }
        //已完成的订单不允许提交
        if ("3".equals(flag)) {
            tv_save.setVisibility(View.INVISIBLE);
            //tv_submit.setVisibility(View.INVISIBLE);
            tv_pz.setVisibility(View.GONE);
        } else {
            tv_save.setVisibility(View.VISIBLE);
            //tv_submit.setVisibility(View.VISIBLE);
            tv_pz.setVisibility(View.VISIBLE);
        }
    }

    private final int REQUEST_IMAGE_CAPTURE = 1;
    private final int REQUEST_IMAGE_EDIT = 2;
    //弹出拍照窗口
    private String mFilePath;

    private void takePhoto() {
        try {
            String guid = String.valueOf(System.currentTimeMillis());
            // 获取SD卡路径
            mFilePath = Environment.getExternalStorageDirectory().getPath() + "/" + SysParameter.PictureDir;
            File dir = new File(mFilePath);
            if (!dir.exists()) {    //exists()判断文件是否存在，不存在则创建文件
                dir.mkdirs();
            }
            String[] content = dir.list();
            for (int i = content.length - 1; i >= 0; i--) {
                File temp = new File(mFilePath, content[i]);
                temp.delete();
            }
            // 保存图片的文件名
            mFilePath = mFilePath + "/" + guid + ".png";

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                takePhotoBiggerThan7(mFilePath);
            } else {
                // 指定拍照意图
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                // 加载路径图片路径
                Uri mUri = Uri.fromFile(new File(mFilePath));
                // 指定存储路径，这样就可以保存原图了
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                } else {
                    Toast.makeText(getApplicationContext(), "无法启动拍照功能", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "拍照失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }

    }

    private void takePhotoBiggerThan7(String absolutePath) {
        Uri mCameraTempUri;
        try {
            ContentValues values = new ContentValues(1);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            values.put(MediaStore.Images.Media.DATA, absolutePath);
            mCameraTempUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            if (mCameraTempUri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraTempUri);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            }
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            } else {
                Toast.makeText(getApplicationContext(), "无法启动拍照功能", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            final Context context = getApplicationContext();
            int readPermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.READ_EXTERNAL_STORAGE);
            int writePermissionCheck = ContextCompat.checkSelfPermission(context,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (readPermissionCheck == PackageManager.PERMISSION_GRANTED && writePermissionCheck == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else {
            //permission is automatically granted on sdk<23 upon installation
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            takePhoto();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            InputStream is = null;
            try {
                // 获取输入流
                is = new FileInputStream(mFilePath);
                // 把流解析成bitmap,此时就得到了清晰的原图
                Bitmap imageBitmap = BitmapFactory.decodeStream(is);
                byte[] bytes = CommonUtil.BitmapToBytes(imageBitmap);
                if (imageBitmap != null) {
                    //拍照上传
                    GetData();
                    CommonUtil.showPress(LogisticsActivity.this);
                    UpdatePhotoTask updatePhotoTask = new UpdatePhotoTask(LogisticsActivity.this, bytes);
                    updatePhotoTask.execute();
                }

            } catch (FileNotFoundException e) {
                Toast.makeText(LogisticsActivity.this, "读文件错误：" + e.getMessage(), Toast.LENGTH_LONG).show();
            } finally {
                // 关闭流
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(LogisticsActivity.this, "关闭文件错误：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        } else if (requestCode == REQUEST_IMAGE_EDIT) {
            //查询已经保存的信息
            CommonUtil.showPress(LogisticsActivity.this);
            QueryTask queryTask = new QueryTask(LogisticsActivity.this);
            queryTask.execute();
        }
    }

    //从编辑框上将数据提取到类对象
    private void GetData() {
        logisticsInfo = new LogisticsInfo();
        logisticsInfo.deliveryId = deliveryBean.deliveryId;
        if (selectedDepotNo >= 0 && selectedDepotNo < logBeanList.size()) {
            logisticsInfo.logisticsId = logBeanList.get(selectedDepotNo).logisticsCompanyID;
            logisticsInfo.logisticsCompany = logBeanList.get(selectedDepotNo).logisticsCompany;
        }
        logisticsInfo.logisticsNo = et_wldh.getUpperText().toString();
        logisticsInfo.deliveryDate = et_shsj.getText().toString();
        logisticsInfo.contact = et_lxr.getUpperText().toString();
        logisticsInfo.telephone1 = et_shdy1.getUpperText().toString();
        logisticsInfo.remark = et_bz.getUpperText().toString();
    }

    //将类对象的数据添加到编辑框上
    private void SetData() {
        if (logisticsInfo != null) {
            for (int i = 0; i < logBeanList.size(); i++) {
                if (logBeanList.get(i).logisticsCompanyID.equals(logisticsInfo.logisticsId)) {
                    spin_logistics.setSelection(i, true);
                    selectedDepotNo = i;
                }
            }
            et_wldh.setText(logisticsInfo.logisticsNo);
            et_lxr.setText(logisticsInfo.contact);
            et_shsj.setText(logisticsInfo.deliveryDate);
            et_shdy1.setText(logisticsInfo.telephone1);
            et_bz.setText(logisticsInfo.remark);
            if (logisticsInfo.strPhotoList != null) {
                DisplayMetrics displayMetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                float density = displayMetrics.density;
                layout_imagelist.removeAllViews();
                for (int i = 0; i < logisticsInfo.strPhotoList.size(); i++) {
                    String url = logisticsInfo.strPhotoList.get(i);
                    ImageView view = new ImageView(LogisticsActivity.this); view.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (48 * density), (int) (48 * density));
                    params.leftMargin = 5;
                    params.bottomMargin = 5;
                    params.topMargin = 5;
                    view.setLayoutParams(params);
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(LogisticsActivity.this, LogisticsPhotoEditActivity.class);
                            intent.putExtra("logisticsInfo", logisticsInfo);
                            intent.putExtra("flag", flag);
                            startActivityForResult(intent, REQUEST_IMAGE_EDIT);
                        }
                    });
                    Picasso.with(LogisticsActivity.this).load(url).into(view);
                    layout_imagelist.addView(view);
                }
            }
        }
    }

    //保存服务
    class SaveTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        SaveTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                msg = WebServiceHelper_Delivery.DELIVERY_07(deliveryBean.deliveryId, logisticsInfo);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                finish();
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //发运服务
    class CommitTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        CommitTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                msg = WebServiceHelper_Delivery.DELIVERY_15(deliveryBean.deliveryId);

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                Toast.makeText(getApplicationContext(), "发运成功", Toast.LENGTH_LONG).show();
                Intent intent = new Intent(LogisticsActivity.this, DeliveryActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询服务
    class QueryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //查询列表数据
                logisticsInfo = WebServiceHelper_Delivery.DELIVERY_08(deliveryBean.deliveryId);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (logisticsInfo != null) {
                    SetData();
                } else {
                    logisticsInfo = new LogisticsInfo();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //上传图片服务
    class UpdatePhotoTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private byte[] photoData;

        UpdatePhotoTask(Context context, byte[] photoData) {
            super();
            mcontext = context;
            this.photoData = photoData;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                //先保存数据
                msg = WebServiceHelper_Delivery.DELIVERY_07(deliveryBean.deliveryId,logisticsInfo);
                if (msg.contains("成功")) {
                    //再上传图片
                    msg = WebServiceHelper_Delivery.DELIVERY_09(deliveryBean.deliveryId, photoData);
                    if (msg.contains("成功")) {
                        //查询结果
                        logisticsInfo = WebServiceHelper_Delivery.DELIVERY_08(deliveryBean.deliveryId);
                        msg = "成功";
                    }
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (logisticsInfo != null) {
                    SetData();
                } else {
                    logisticsInfo = new LogisticsInfo();
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //绑定物流公司
    private void SetSpanLog(Context context) {
        spin_logistics = findViewById(R.id.spin_logistics);
        for (int i = 0; i < logBeanList.size(); i++) {
            LogisticsInfoList.add(logBeanList.get(i).logisticsCompany);
        }
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.style_spinner, LogisticsInfoList);
        adapter2.setDropDownViewResource(R.layout.style_spinner_item);//自定义样式
        spin_logistics.setAdapter(adapter2);
        spin_logistics.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedDepotNo = position;
                if (selectedDepotNo >= 0 && selectedDepotNo < logBeanList.size()) {
                    String shdy = logBeanList.get(selectedDepotNo).telephone;
                    String lxr = logBeanList.get(selectedDepotNo).contact;
                    et_shdy1.setText(shdy);
                    et_lxr.setText(lxr);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    //查询物流
    private void QueryLogistics() {
        LogisticsActivity.QueryLogisticsTask queryLogisticsTask = new LogisticsActivity.QueryLogisticsTask(LogisticsActivity.this);
        queryLogisticsTask.execute();
    }

    class QueryLogisticsTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";

        QueryLogisticsTask(Context context) {
            super();
            mcontext = context;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                logBeanList = WebServiceHelper_Delivery.DELIVERY_10(deliveryBean.depotId);
                msg = "成功";

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            if (msg.contains("成功")) {
                SetSpanLog(mcontext);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //以下为扫码相关
    @Override
    protected void onPause() {
        super.onPause();
        unRegisterReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver();
    }

    //注册广播
    private void registerReceiver() {
        IntentFilter intFilter = new IntentFilter(ScanManager.ACTION_SEND_SCAN_RESULT);
        registerReceiver(mResultReceiver, intFilter);
    }

    //取消注册广播
    private void unRegisterReceiver() {
        try {
            unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
            Toast.makeText(this, "注销扫码失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    //监听扫码数据的广播，当设置广播输出时作用该方法获取扫码数据
    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ScanManager.ACTION_SEND_SCAN_RESULT.equals(action)) {
                byte[] bvalue1 = intent.getByteArrayExtra(ScanManager.EXTRA_SCAN_RESULT_ONE_BYTES);
                String svalue1 = null;
                try {
                    if (bvalue1 != null) {
                        svalue1 = new String(bvalue1, "GBK");
                        et_wldh.setText(svalue1);
                        /*BarCodeBean barCodeBean = CommonUtil.ParseBarCodeNew(svalue1);
                        if (barCodeBean == null || barCodeBean.barType == BarCodeBean.BAR_UNKNOWN) {
                            Toast.makeText(ShelvesPartQueryActivity.this, "无效二维码：" + svalue1, Toast.LENGTH_LONG).show();
                        } else if (barCodeBean.barType == BarCodeBean.BAR_SHELVES) {
                            Toast.makeText(ShelvesPartQueryActivity.this, "请扫描配件，不要扫描货架", Toast.LENGTH_LONG).show();
                        } else {
                            CommonUtil.showPress(ShelvesPartQueryActivity.this);
                            ShelvesPartQueryActivity.PartQueryAndToShelvesTask partQueryAndToShelvesTask = new ShelvesPartQueryActivity.PartQueryAndToShelvesTask(ShelvesPartQueryActivity.this, svalue1);
                            partQueryAndToShelvesTask.execute();
                        }*/
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(LogisticsActivity.this, "扫描失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
    };


}
